import { useState } from "react";
import styles from "./index.module.less";
import SearchBox from "@/components/SearchBox";
import { SEARCH_COLUMNS, TABLE_COLUMNS } from "./constant";
import { Modal, message } from "antd";
import SuperTable from "@/components/SuperTable";
import { useNavigate } from "react-router-dom";
import { deleteShopsApi, getShopsListApi, updateShopsStatusApi } from "@/api/modules/merchant";
import { ShopStatus } from "@/enums";
import { RESULT_CODES } from "@/api/helper/ResultCode";

export default () => {
	const [params, setParams] = useState({});
	const navigate = useNavigate();

	const handleSearch = e => {
		setParams(e);
	};

	const handleRequest = async (params: any) => {
		const res = await getShopsListApi({
			limit: params.pageSize,
			page: params.current,
			keyword: params.keyword ?? "",
			shop_status: params.shop_status ?? ""
		});
		return {
			total: res?.total ?? 0,
			data: res?.data ?? []
		};
	};

	const handleStatusChange = (data: any) => {
		updateShopsStatusApi(data).then(res => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				message.success("操作成功");
				setParams(e => ({
					...e,
					timeStamp: Date.now()
				}));
			}
		});
	};

	const newColumns = [
		...TABLE_COLUMNS,
		{
			title: "操作",
			width: 220,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "edit":
						navigate("/merchant/info", { state: { data: record, isEdit: true } });
						break;
					case "up":
						handleStatusChange({
							shop_id: record.shop_id,
							shop_status: ShopStatus.OPEN
						});
						break;
					case "down":
						handleStatusChange({
							shop_id: record.shop_id,
							shop_status: ShopStatus.DOWN
						});
						break;
					case "delete":
						Modal.confirm({
							icon: null,
							title: "确认删除该内容？",
							content: "内容删除后讲无法恢复，请慎重考虑",
							closable: true,
							onOk: c => {
								deleteShopsApi({
									shop_return_addresses_id: record.shop_return_addresses_id,
									shop_id: record.shop_id
								}).then(res => {
									if (res?.code === RESULT_CODES.SUCCESS) {
										message.success("删除成功");
										setParams(e => ({
											...e,
											timeStamp: Date.now()
										}));
										c?.();
									}
								});
							}
						});

						break;
				}
			},
			options: (record: any) => {
				//是否在营业中
				const isOpening = record.shop_status === ShopStatus.OPEN;
				return [
					{
						label: "编辑",
						value: "edit"
					},
					{
						label: isOpening ? "下架" : "上架",
						value: isOpening ? "down" : "up"
					},
					{
						label: "删除",
						value: "delete"
					}
				];
			}
		}
	];

	return (
		<div className={styles.container}>
			<SearchBox columns={SEARCH_COLUMNS} onSearch={handleSearch} />
			<SuperTable params={params} columns={newColumns} request={handleRequest} scroll={{ x: "900" }} />
		</div>
	);
};
